package com.chap18;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

/**
 * <p>
 * <code>BiasedLockingTest</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-05-24 10:35
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class BiasedLockingTest2 {
    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(5000);
        List<Object> locks= new ArrayList<>();
        new Thread(()->{
            for (int i = 0; i < 41 ; i++) {
                Object lock = new BiasedLockingTest2();
                synchronized (lock){//50个偏向锁 偏向thread1
                    locks.add(lock);
                }
            }

            try {
                //防止jvm线程复用，保持线程thread1状态为存活
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thread1").start();

        //睡眠 保证thread1创建对象完成
        Thread.sleep(3000);

        log.debug("打印thread1,list中第20个对象的对象头：");
        log.debug((ClassLayout.parseInstance(locks.get(19)).toPrintable()));

        new Thread(()->{
            for (int i = 0; i < 41; i++) {
                Object lock = locks.get(i);
                synchronized (lock){
                    //1-19次 偏向锁撤销 ，拿到的是轻量级锁，20包含20次以后拿到的是偏向锁
                    if (i>=15 && i<=21 || i>=38){
                        log.debug(("thread2-第" + (i + 1) + "次加锁执行中\t"+ClassLayout.parseInstance(lock).toPrintable()));

                    }
                }

            }

            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thread2").start();

        Thread.sleep(3000);

        new Thread(()->{
            for (int i = 0; i < 41; i++) {
                Object lock =locks.get(i);
                if(i>=17&&i<=21){
                    log.debug("thread3-第" + (i + 1) + "次准备加锁\t"+
                            ClassLayout.parseInstance(lock).toPrintable());
                }
                synchronized (lock){
                    if(i>=17&&i<=21){
                        log.debug("thread3-第" + (i + 1) + "次加锁执行中\t"+
                                ClassLayout.parseInstance(lock).toPrintable());
                    }
                }

            }
        },"thread3").start();

        Thread.sleep(3000);
        log.debug("查看新创建的对象");
        log.debug((ClassLayout.parseInstance(new BiasedLockingTest()).toPrintable()));

        LockSupport.park();
    }
}
